<template>
  <div class="my-clue">
    <!-- 主页面内容（支持右侧弹窗时移位） -->
    <div class="main-content" :class="{ 'shift-left': isRightDialogOpen }">
      <div class="top-filter">
        <div class="top-filter-left">
          <stick-popup>
            <template #show>
              <div class="top-filter-btn">
                <div class="top-filter-btn-label">筛选</div>
                <div class="top-filter-btn-icon">
                  <Operation />
                </div>
              </div>
            </template>
            <template #content>
              <div class="top-filter-form">
                <el-form :model="form" label-width="100px">
                  <!-- 订单审核状态 -->
                  <el-form-item label="订单审核状态">
                    <el-select v-model="form.orderAuditStatus" placeholder="请选择">
                      <el-option label="待提交" value="待提交"></el-option>
                      <el-option label="待订单审核" value="待订单审核"></el-option>
                      <el-option label="订单审核不通过" value="订单审核不通过"></el-option>
                      <el-option label="待财务审核" value="待财务审核"></el-option>
                      <el-option label="财务审核不通过" value="财务审核不通过"></el-option>
                      <el-option label="执行中" value="执行中"></el-option>
                      <el-option label="已结束" value="已结束"></el-option>
                      <el-option label="已终止" value="已终止"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 项目完成情况 -->
                  <el-form-item label="项目完成情况">
                    <el-select v-model="form.projectCompletion" placeholder="请选择">
                      <el-option label="全部完成" value="全部完成"></el-option>
                      <el-option label="部分完成" value="部分完成"></el-option>
                      <el-option label="未完成" value="未完成"></el-option>
                      <el-option label="无关联项目" value="无关联项目"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 客户状态 -->
                  <el-form-item label="客户状态">
                    <el-select v-model="form.customerStatus" placeholder="请选择">
                      <el-option label="正常" value="正常"></el-option>
                      <el-option label="暂停" value="暂停"></el-option>
                      <el-option label="流失" value="流失"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 有无附件 -->
                  <el-form-item label="有无附件">
                    <el-select v-model="form.hasAttachment" placeholder="请选择">
                      <el-option label="有" value="有"></el-option>
                      <el-option label="无" value="无"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 订单审核人 -->
                  <el-form-item label="订单审核人">
                    <el-select v-model="form.orderAuditor" placeholder="搜索订单审核人">
                      <el-option label="审核人1" value="审核人1"></el-option>
                      <el-option label="审核人2" value="审核人2"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 服务产品 -->
                  <el-form-item label="服务产品">
                    <el-select v-model="form.serviceProduct" placeholder="搜索服务产品">
                      <el-option label="产品A" value="产品A"></el-option>
                      <el-option label="产品B" value="产品B"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 服务项目 -->
                  <el-form-item label="服务项目">
                    <el-select v-model="form.serviceItem" placeholder="搜索服务项目">
                      <el-option label="项目1" value="项目1"></el-option>
                      <el-option label="项目2" value="项目2"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 收费负责人 -->
                  <el-form-item label="收费负责人">
                    <el-select v-model="form.chargePerson" placeholder="搜索收费负责人">
                      <el-option label="负责人1" value="负责人1"></el-option>
                      <el-option label="负责人2" value="负责人2"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 签单人部门 + 部门包含下级 -->
                  <el-form-item label="签单人部门">
                    <el-select v-model="form.signerDept" placeholder="搜索签单人部门">
                      <el-option label="销售一部" value="销售一部"></el-option>
                      <el-option label="销售二部" value="销售二部"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-checkbox v-model="form.includeSubDept" label="部门包含下级" />
                  </el-form-item>

                  <!-- 签单时间范围 -->
                  <el-form-item label="签单时间">
                    <el-date-picker v-model="form.signTime" type="daterange" range-separator="到" start-placeholder="开始日期"
                      end-placeholder="结束日期" />
                  </el-form-item>

                  <!-- 内部推荐人 -->
                  <el-form-item label="内部推荐人">
                    <el-select v-model="form.internalRecommender" placeholder="搜索内部推荐人">
                      <el-option label="推荐人1" value="推荐人1"></el-option>
                      <el-option label="推荐人2" value="推荐人2"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 客户标签 -->
                  <el-form-item label="客户标签">
                    <el-select v-model="form.customerTag" placeholder="搜索客户标签">
                      <el-option label="标签1" value="标签1"></el-option>
                      <el-option label="标签2" value="标签2"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 行业分类 -->
                  <el-form-item label="行业分类">
                    <el-select v-model="form.industryCategory" placeholder="搜索行业分类">
                      <el-option label="互联网" value="互联网"></el-option>
                      <el-option label="金融" value="金融"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 其他推荐人 -->
                  <el-form-item label="其他推荐人">
                    <el-input v-model="form.otherRecommender" placeholder="搜索其他推荐人" />
                  </el-form-item>

                  <!-- 客户所属部门 + 部门包含下级 -->
                  <el-form-item label="客户所属部门">
                    <el-select v-model="form.customerDept" placeholder="搜索客户所属部门">
                      <el-option label="技术部" value="技术部"></el-option>
                      <el-option label="产品部" value="产品部"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-checkbox v-model="form.includeSubCustomerDept" label="部门包含下级" />
                  </el-form-item>

                  <!-- 来源 -->
                  <el-form-item label="来源">
                    <el-select v-model="form.source" placeholder="请选择">
                      <el-option label="来源1" value="来源1"></el-option>
                      <el-option label="来源2" value="来源2"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 片区 -->
                  <el-form-item label="片区">
                    <el-select v-model="form.area" placeholder="搜索片区">
                      <el-option label="片区1" value="片区1"></el-option>
                      <el-option label="片区2" value="片区2"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 订单审核时间范围 -->
                  <el-form-item label="订单审核时间">
                    <el-date-picker v-model="form.orderAuditTime" type="daterange" range-separator="到"
                      start-placeholder="开始日期" end-placeholder="结束日期" />
                  </el-form-item>

                  <!-- 财务审核时间范围 -->
                  <el-form-item label="财务审核时间">
                    <el-date-picker v-model="form.financialAuditTime" type="daterange" range-separator="到"
                      start-placeholder="开始日期" end-placeholder="结束日期" />
                  </el-form-item>

                  <!-- 订单完结时间范围 -->
                  <el-form-item label="订单完结时间">
                    <el-date-picker v-model="form.orderEndTime" type="daterange" range-separator="到"
                      start-placeholder="开始日期" end-placeholder="结束日期" />
                  </el-form-item>

                  <!-- 完结人 -->
                  <el-form-item label="完结人">
                    <el-select v-model="form.finisher" placeholder="搜索完结人">
                      <el-option label="完结人1" value="完结人1"></el-option>
                      <el-option label="完结人2" value="完结人2"></el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 开票状态 -->
                  <el-form-item label="开票状态">
                    <el-select v-model="form.invoiceStatus" placeholder="请选择">
                      <el-option label="未开票" value="未开票"></el-option>
                      <el-option label="部分开票" value="部分开票"></el-option>
                      <el-option label="已开完" value="已开完"></el-option>
                      <el-option label="无需开票" value="无需开票"></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </template>
            <template #footer>
              <div class="top-filter-operate">
                <el-button type="text" @click="resetFilterForm">取消</el-button>
                <el-button type="primary" @click="handleFilterSubmit">确定</el-button>
              </div>
            </template>
          </stick-popup>
          <div class="top-filter-search">
            <el-input v-model="input1" placeholder="搜索订单/客户信息" @keyup.enter="handleSearch">
              <template #append>
                <el-button :icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </div>
          <div class="top-filter-checkbox">
            <el-checkbox v-model="checked1" label="包含已取消订单" size="default" border />
          </div>
        </div>
        <div class="top-filter-right">
          <!-- 新增订单按钮（绑定弹窗事件） -->
          <el-button type="primary" @click="openCustomerSearchDialog">
            <Plus style="margin-right: 5px;" />新增订单
          </el-button>
          <el-button type="primary">批量操作</el-button>
          <el-button type="primary">导出</el-button>
        </div>
      </div>

      <div class="table-area">
        <div class="table-area-tab">
          <div class="tab-wrapper">
            <!-- 主标签页：全部、待提交、审核不通过、未收款 -->
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="(tab) => handleTabChange(tab.name)" stretch>
              <el-tab-pane label="全部" name="all"></el-tab-pane>
              <el-tab-pane label="待提交" name="toSubmit"></el-tab-pane>
              <el-tab-pane label="审核不通过" name="auditFailed"></el-tab-pane>
              <el-tab-pane label="未收款" name="uncollected"></el-tab-pane>
            </el-tabs>

            <!-- 更多标签下拉菜单 -->
            <el-dropdown @command="handleTabChange" trigger="click">
              <div class="more-tab">
                更多
                <el-icon class="arrow-icon">
                  <ArrowDown />
                </el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="partiallyCollected">部分收款</el-dropdown-item>
                  <el-dropdown-item command="fullyCollected">完成收款</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>

        <div class="table-area-table">
          <my-table :loading="loading" :columns="columns" :dataSource="mockData" :showIndex="true"
            :show-operation="false">
            <!-- 订单状态格式化 -->
            <template #data-orderStatus="scope">
              <el-tag :type="scope.data === '已完成' ? 'success' :
                scope.data === '已审核' ? 'primary' :
                  scope.data === '待提交' ? 'info' :
                    scope.data === '审核不通过' ? 'danger' :
                      scope.data === '部分收款' ? 'warning' : 'primary'">
                {{ scope.data }}
              </el-tag>
            </template>

            <!-- 金额格式化 -->
            <template #data-orderAmount="scope">
              ¥{{ scope.data.toFixed(2) }}
            </template>
            <template #data-registeredIncome="scope">
              ¥{{ scope.data.toFixed(2) }}
            </template>
            <template #data-uncollectedAmount="scope">
              ¥{{ scope.data.toFixed(2) }}
            </template>
            <template #data-auditedIncome="scope">
              ¥{{ scope.data.toFixed(2) }}
            </template>
            <template #data-expendAmount="scope">
              ¥{{ scope.data.toFixed(2) }}
            </template>
            <template #data-refundAmount="scope">
              ¥{{ scope.data.toFixed(2) }}
            </template>

            <!-- 筛选器插槽 -->
            <template #filter-orderStatus>
              <span>订单状态</span>
              <el-icon class="filter-icon">
                <Filter />
              </el-icon>
            </template>
            <template #filter-customerDepartment>
              <span>客户部门</span>
              <el-icon class="filter-icon">
                <Filter />
              </el-icon>
            </template>
          </my-table>
        </div>
      </div>
    </div>

    <!-- 右侧弹窗：客户搜索 -->
    <div class="right-dialog" v-if="customerSearchDialogVisible">
      <div class="dialog-header">
        <h3>选择客户</h3>
        <el-button type="text" class="close-btn" @click="closeCustomerSearchDialog">×</el-button>
      </div>
      <div class="dialog-toolbar">
        <el-button 
          type="text" 
          class="add-customer-btn" 
          @click="showAddCustomer = true"
        >
          <Plus style="margin-right: 3px;" />新增客户
        </el-button>
      </div>
      <div class="dialog-body">
        <el-input 
          v-model="customerSearchKey" 
          placeholder="请输入客户简称、客户编号或税号搜索" 
          @input="handleCustomerSearch"
          clearable
          size="large"
        >
          <template #append>
            <el-button :icon="Search" @click="handleCustomerSearch" />
          </template>
        </el-input>
        
        <div class="customer-list">
          <el-table 
            :data="filteredCustomers" 
            border 
            style="width: 100%; margin-top: 15px"
            @row-click="selectCustomer"
            highlight-current-row
          >
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <el-table-column prop="customerNo" label="客户编号" width="120"></el-table-column>
            <el-table-column prop="customerShortName" label="客户简称" width="180"></el-table-column>
            <el-table-column prop="taxNo" label="税号"></el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button 
                  type="text" 
                  size="small" 
                  @click.stop="selectCustomer(scope.row)"
                >
                  选择
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="filteredCustomers.length === 0" class="no-data">
            <div class="no-data-icon">
              <Search />
            </div>
            <div class="no-data-text">没有找到匹配的客户</div>
            <div class="no-data-hint">请尝试其他关键词或新增客户</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧弹窗：新增订单 -->
    <div class="right-dialog" v-if="addOrderDialogVisible">
      <div class="dialog-header">
        <h3>新增订单</h3>
        <el-button type="text" class="close-btn" @click="closeAddOrderDialog">×</el-button>
      </div>
      <div class="dialog-body">
        <el-form 
          :model="newOrderForm" 
          label-width="120px" 
          class="new-order-form"
          :rules="orderRules"
          ref="orderFormRef"
        >
          <el-form-item label="客户编号" prop="customerNo">
            <el-input v-model="newOrderForm.customerNo" disabled></el-input>
          </el-form-item>
          <el-form-item label="客户简称" prop="customerShortName">
            <el-input v-model="newOrderForm.customerShortName" disabled></el-input>
          </el-form-item>
          <el-form-item label="服务项" prop="serviceItem">
            <el-input v-model="newOrderForm.serviceItem" placeholder="请输入服务项"></el-input>
          </el-form-item>
          <el-form-item label="订单金额" prop="orderAmount">
            <el-input 
              v-model.number="newOrderForm.orderAmount" 
              placeholder="请输入订单金额" 
              prefix="¥"
            ></el-input>
          </el-form-item>
          <el-form-item label="签单人" prop="signer">
            <el-input v-model="newOrderForm.signer" placeholder="请输入签单人"></el-input>
          </el-form-item>
          <el-form-item label="关联项目" prop="relatedProject">
            <el-input v-model="newOrderForm.relatedProject" placeholder="请输入关联项目"></el-input>
          </el-form-item>
          <el-form-item label="订单备注" prop="remark">
            <el-input 
              v-model="newOrderForm.remark" 
              placeholder="请输入订单备注信息" 
              type="textarea"
              rows="3"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer">
        <el-button @click="closeAddOrderDialog">取消</el-button>
        <el-button type="primary" @click="submitNewOrder">提交订单</el-button>
      </div>
    </div>

    <!-- 新增客户弹窗 -->
    <el-dialog 
      title="新增客户" 
      v-model="showAddCustomer" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="newCustomerForm" 
        label-width="100px" 
        class="new-customer-form"
        :rules="customerRules"
        ref="customerFormRef"
      >
        <el-form-item label="客户编号" prop="customerNo">
          <el-input v-model="newCustomerForm.customerNo" placeholder="请输入客户编号"></el-input>
        </el-form-item>
        <el-form-item label="客户简称" prop="customerShortName">
          <el-input v-model="newCustomerForm.customerShortName" placeholder="请输入客户简称"></el-input>
        </el-form-item>
        <el-form-item label="税号" prop="taxNo">
          <el-input v-model="newCustomerForm.taxNo" placeholder="请输入客户税号"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddCustomer = false">取消</el-button>
        <el-button type="primary" @click="submitNewCustomer">保存客户</el-button>
      </template>
    </el-dialog>

    <!-- 遮罩层 -->
    <div 
      class="overlay" 
      v-if="isRightDialogOpen" 
      @click="closeAllRightDialogs"
    ></div>
  </div>
</template>

<script setup>
import MyTable from '@/components/MyTable.vue';
import StickPopup from '@/components/StickPopup.vue';
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Search, Operation, Filter, ArrowDown, Plus } from '@element-plus/icons-vue'

// 订单列数据
const columns = [
  { title: '订单编号', key: 'orderNo', sortable: true },
  { title: '客户简称', key: 'customerShortName', sortable: true },
  { title: '客户编号', key: 'customerNo', sortable: true },
  { title: '服务项', key: 'serviceItem' },
  { title: '订单状态', key: 'orderStatus', sortable: true, filterable: true },
  { title: '订单金额', key: 'orderAmount', sortable: true },
  { title: '已登记收入', key: 'registeredIncome', sortable: true },
  { title: '未收金额', key: 'uncollectedAmount', sortable: true },
  { title: '已审核收入', key: 'auditedIncome', sortable: true },
  { title: '支出金额', key: 'expendAmount', sortable: true },
  { title: '退款金额', key: 'refundAmount', sortable: true },
  { title: '客户所属部门', key: 'customerDepartment', filterable: true },
  { title: '签单人', key: 'signer', filterable: true },
  { title: '签单人部门', key: 'signerDepartment', filterable: true },
  { title: '关联项目', key: 'relatedProject' },
];

const mockData = ref([]);
const loading = ref(true);
const activeName = ref('all'); // 默认选中"全部"

// 响应式变量
const form = ref({});
const input1 = ref('');
const checked1 = ref(false);

// 弹窗状态管理（统一控制右侧弹窗）
const customerSearchDialogVisible = ref(false);
const addOrderDialogVisible = ref(false);
const showAddCustomer = ref(false);
const customerSearchKey = ref('');
const filteredCustomers = ref([]);

// 客户数据（模拟现有客户列表）
const customerData = ref([
  { customerNo: 'CUS001', customerShortName: '阿里科技', taxNo: '91330100768231165X' },
  { customerNo: 'CUS002', customerShortName: '腾讯科技', taxNo: '91440300708461136T' },
  { customerNo: 'CUS003', customerShortName: '百度在线', taxNo: '91110000802100433B' },
  { customerNo: 'CUS004', customerShortName: '字节跳动', taxNo: '91110108335469089C' },
  { customerNo: 'CUS005', customerShortName: '京东集团', taxNo: '911100006669699992' },
  { customerNo: 'CUS006', customerShortName: '美团点评', taxNo: '91110108351593388C' },
  { customerNo: 'CUS007', customerShortName: '拼多多', taxNo: '91310115MA1G0K1W43' },
  { customerNo: 'CUS008', customerShortName: '网易', taxNo: '91330000142910548R' },
  { customerNo: 'CUS009', customerShortName: '小米科技', taxNo: '91110108551385082Q' },
  { customerNo: 'CUS010', customerShortName: '华为技术', taxNo: '91440300746645251H' },
]);

// 新增订单表单数据
const newOrderForm = reactive({
  customerNo: '',
  customerShortName: '',
  serviceItem: '',
  orderAmount: 0,
  signer: '',
  relatedProject: '',
  remark: ''
});

// 新增客户表单数据
const newCustomerForm = reactive({
  customerNo: '',
  customerShortName: '',
  taxNo: ''
});

// 表单验证规则
const orderRules = ref({
  serviceItem: [{ required: true, message: '请输入服务项', trigger: 'blur' }],
  orderAmount: [
    { required: true, message: '请输入订单金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '订单金额必须大于0', trigger: 'blur' }
  ],
  signer: [{ required: true, message: '请输入签单人', trigger: 'blur' }]
});

const customerRules = ref({
  customerNo: [{ required: true, message: '请输入客户编号', trigger: 'blur' }],
  customerShortName: [{ required: true, message: '请输入客户简称', trigger: 'blur' }],
  taxNo: [{ required: true, message: '请输入客户税号', trigger: 'blur' }]
});

// 表单引用
const orderFormRef = ref(null);
const customerFormRef = ref(null);

// 计算属性：控制主内容区移位
const isRightDialogOpen = computed(() => {
  return customerSearchDialogVisible.value || addOrderDialogVisible.value;
});

// 处理标签页和更多选项的点击事件
const handleTabChange = (tabKey) => {
  loading.value = true;
  activeName.value = tabKey;

  setTimeout(() => {
    // 按新标签页逻辑加载对应数据
    switch (tabKey) {
      case 'all':
        // 全部订单（包含所有状态）
        mockData.value = [
          {
            orderNo: 'ORD2023001',
            customerShortName: '阿里科技',
            customerNo: 'CUS001',
            serviceItem: '云服务套餐',
            orderStatus: '已完成',
            orderAmount: 12000,
            registeredIncome: 12000,
            uncollectedAmount: 0,
            auditedIncome: 12000,
            expendAmount: 3000,
            refundAmount: 0,
            customerDepartment: '技术部',
            signer: '张三',
            signerDepartment: '销售一部',
            relatedProject: '企业云迁移'
          },
          {
            orderNo: 'ORD2023002',
            customerShortName: '腾讯科技',
            customerNo: 'CUS002',
            serviceItem: '数据分析服务',
            orderStatus: '待提交',
            orderAmount: 25000,
            registeredIncome: 0,
            uncollectedAmount: 25000,
            auditedIncome: 0,
            expendAmount: 0,
            refundAmount: 0,
            customerDepartment: '数据中心',
            signer: '李四',
            signerDepartment: '销售二部',
            relatedProject: '用户行为分析'
          },
          {
            orderNo: 'ORD2023003',
            customerShortName: '百度在线',
            customerNo: 'CUS003',
            serviceItem: 'AI接口服务',
            orderStatus: '审核不通过',
            orderAmount: 8000,
            registeredIncome: 0,
            uncollectedAmount: 8000,
            auditedIncome: 0,
            expendAmount: 0,
            refundAmount: 0,
            customerDepartment: 'AI实验室',
            signer: '王五',
            signerDepartment: '销售一部',
            relatedProject: '智能推荐系统'
          },
          {
            orderNo: 'ORD2023004',
            customerShortName: '字节跳动',
            customerNo: 'CUS004',
            serviceItem: '短视频解决方案',
            orderStatus: '已审核',
            orderAmount: 30000,
            registeredIncome: 0,
            uncollectedAmount: 30000,
            auditedIncome: 30000,
            expendAmount: 5000,
            refundAmount: 0,
            customerDepartment: '产品部',
            signer: '赵六',
            signerDepartment: '销售三部',
            relatedProject: '内容生态建设'
          }
        ];
        break;
      case 'toSubmit':
        // 待提交订单（未提交审核的订单）
        mockData.value = [
          {
            orderNo: 'ORD2023002',
            customerShortName: '腾讯科技',
            customerNo: 'CUS002',
            serviceItem: '数据分析服务',
            orderStatus: '待提交',
            orderAmount: 25000,
            registeredIncome: 0,
            uncollectedAmount: 25000,
            auditedIncome: 0,
            expendAmount: 0,
            refundAmount: 0,
            customerDepartment: '数据中心',
            signer: '李四',
            signerDepartment: '销售二部',
            relatedProject: '用户行为分析'
          },
          {
            orderNo: 'ORD2023005',
            customerShortName: '京东集团',
            customerNo: 'CUS005',
            serviceItem: '物流系统升级',
            orderStatus: '待提交',
            orderAmount: 50000,
            registeredIncome: 0,
            uncollectedAmount: 50000,
            auditedIncome: 0,
            expendAmount: 0,
            refundAmount: 0,
            customerDepartment: '物流部',
            signer: '孙七',
            signerDepartment: '销售四部',
            relatedProject: '智能仓储建设'
          }
        ];
        break;
      case 'auditFailed':
        // 审核不通过订单
        mockData.value = [
          {
            orderNo: 'ORD2023003',
            customerShortName: '百度在线',
            customerNo: 'CUS003',
            serviceItem: 'AI接口服务',
            orderStatus: '审核不通过',
            orderAmount: 8000,
            registeredIncome: 0,
            uncollectedAmount: 8000,
            auditedIncome: 0,
            expendAmount: 0,
            refundAmount: 0,
            customerDepartment: 'AI实验室',
            signer: '王五',
            signerDepartment: '销售一部',
            relatedProject: '智能推荐系统'
          },
          {
            orderNo: 'ORD2023006',
            customerShortName: '美团点评',
            customerNo: 'CUS006',
            serviceItem: '外卖系统维护',
            orderStatus: '审核不通过',
            orderAmount: 15000,
            registeredIncome: 0,
            uncollectedAmount: 15000,
            auditedIncome: 0,
            expendAmount: 0,
            refundAmount: 0,
            customerDepartment: '技术研发部',
            signer: '周八',
            signerDepartment: '销售二部',
            relatedProject: '系统稳定性优化'
          }
        ];
        break;
      case 'uncollected':
        // 未收款订单（已审核但未收款）
        mockData.value = [
          {
            orderNo: 'ORD2023004',
            customerShortName: '字节跳动',
            customerNo: 'CUS004',
            serviceItem: '短视频解决方案',
            orderStatus: '已审核',
            orderAmount: 30000,
            registeredIncome: 0,
            uncollectedAmount: 30000,
            auditedIncome: 30000,
            expendAmount: 5000,
            refundAmount: 0,
            customerDepartment: '产品部',
            signer: '赵六',
            signerDepartment: '销售三部',
            relatedProject: '内容生态建设'
          },
          {
            orderNo: 'ORD2023007',
            customerShortName: '拼多多',
            customerNo: 'CUS007',
            serviceItem: '电商平台搭建',
            orderStatus: '已审核',
            orderAmount: 45000,
            registeredIncome: 0,
            uncollectedAmount: 45000,
            auditedIncome: 45000,
            expendAmount: 10000,
            refundAmount: 0,
            customerDepartment: '平台部',
            signer: '吴九',
            signerDepartment: '销售一部',
            relatedProject: '新电商生态'
          }
        ];
        break;
      case 'partiallyCollected':
        // 部分收款订单
        mockData.value = [
          {
            orderNo: 'ORD2023008',
            customerShortName: '网易',
            customerNo: 'CUS008',
            serviceItem: '企业邮箱服务',
            orderStatus: '部分收款',
            orderAmount: 20000,
            registeredIncome: 10000,
            uncollectedAmount: 10000,
            auditedIncome: 20000,
            expendAmount: 3000,
            refundAmount: 0,
            customerDepartment: '行政部',
            signer: '郑十',
            signerDepartment: '销售三部',
            relatedProject: '企业通信系统升级'
          },
          {
            orderNo: 'ORD2023009',
            customerShortName: '小米科技',
            customerNo: 'CUS009',
            serviceItem: '智能硬件测试',
            orderStatus: '部分收款',
            orderAmount: 35000,
            registeredIncome: 15000,
            uncollectedAmount: 20000,
            auditedIncome: 35000,
            expendAmount: 8000,
            refundAmount: 0,
            customerDepartment: '测试部',
            signer: '钱十一',
            signerDepartment: '销售四部',
            relatedProject: '智能家居生态'
          }
        ];
        break;
      case 'fullyCollected':
        // 完成收款订单
        mockData.value = [
          {
            orderNo: 'ORD2023001',
            customerShortName: '阿里科技',
            customerNo: 'CUS001',
            serviceItem: '云服务套餐',
            orderStatus: '已完成',
            orderAmount: 12000,
            registeredIncome: 12000,
            uncollectedAmount: 0,
            auditedIncome: 12000,
            expendAmount: 3000,
            refundAmount: 0,
            customerDepartment: '技术部',
            signer: '张三',
            signerDepartment: '销售一部',
            relatedProject: '企业云迁移'
          },
          {
            orderNo: 'ORD2023010',
            customerShortName: '华为技术',
            customerNo: 'CUS010',
            serviceItem: '5G解决方案',
            orderStatus: '已完成',
            orderAmount: 150000,
            registeredIncome: 150000,
            uncollectedAmount: 0,
            auditedIncome: 150000,
            expendAmount: 45000,
            refundAmount: 0,
            customerDepartment: '研发中心',
            signer: '孙十二',
            signerDepartment: '销售五部',
            relatedProject: '5G基站建设'
          }
        ];
        break;
    }
    loading.value = false;
  }, 800);
};

// 筛选表单提交
const handleFilterSubmit = () => {
  loading.value = true;
  // 这里可以添加实际筛选逻辑
  setTimeout(() => {
    loading.value = false;
    // 示例：基于当前标签页数据进行筛选
    const filtered = mockData.value.filter(item => {
      if (form.value.orderNo && !item.orderNo.includes(form.value.orderNo)) return false;
      if (form.value.customerShortName && !item.customerShortName.includes(form.value.customerShortName)) return false;
      if (form.value.orderStatus && item.orderStatus !== form.value.orderStatus) return false;
      if (form.value.signer && !item.signer.includes(form.value.signer)) return false;
      return true;
    });
    mockData.value = filtered;
  }, 500);
};

// 重置筛选表单
const resetFilterForm = () => {
  form.value = {};
  // 重新加载当前标签页数据
  handleTabChange(activeName.value);
};

// 搜索功能
const handleSearch = () => {
  if (!input1.value) {
    // 搜索为空时重新加载当前标签页数据
    handleTabChange(activeName.value);
    return;
  }

  loading.value = true;
  setTimeout(() => {
    const keyword = input1.value.toLowerCase();
    const filtered = mockData.value.filter(item => {
      return item.orderNo.toLowerCase().includes(keyword) ||
        item.customerShortName.toLowerCase().includes(keyword) ||
        item.customerNo.toLowerCase().includes(keyword);
    });
    mockData.value = filtered;
    loading.value = false;
  }, 500);
};

// 客户搜索逻辑
const handleCustomerSearch = () => {
  if (!customerSearchKey.value) {
    filteredCustomers.value = [...customerData.value];
    return;
  }
  
  const keyword = customerSearchKey.value.toLowerCase();
  filteredCustomers.value = customerData.value.filter(customer => 
    customer.customerShortName.toLowerCase().includes(keyword) ||
    customer.customerNo.toLowerCase().includes(keyword) ||
    customer.taxNo.toLowerCase().includes(keyword)
  );
};

// 弹窗控制方法
const openCustomerSearchDialog = () => {
  customerSearchKey.value = '';
  filteredCustomers.value = [...customerData.value];
  customerSearchDialogVisible.value = true;
  addOrderDialogVisible.value = false;
};

const closeCustomerSearchDialog = () => {
  customerSearchDialogVisible.value = false;
};

const closeAddOrderDialog = () => {
  addOrderDialogVisible.value = false;
  orderFormRef.value?.resetFields();
};

const closeAllRightDialogs = () => {
  customerSearchDialogVisible.value = false;
  addOrderDialogVisible.value = false;
};

// 选择客户后跳转至新增订单
const selectCustomer = (customer) => {
  newOrderForm.customerNo = customer.customerNo;
  newOrderForm.customerShortName = customer.customerShortName;
  customerSearchDialogVisible.value = false;
  addOrderDialogVisible.value = true;
};

// 提交新增订单
const submitNewOrder = async () => {
  try {
    await orderFormRef.value.validate();
    
    // 生成唯一订单编号（年份+时间戳后6位+3位随机数）
    const timestamp = Date.now().toString().slice(-6);
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    const newOrderNo = `ORD${new Date().getFullYear()}${timestamp}${random}`;
    
    // 构建新订单数据
    const newOrder = {
      orderNo: newOrderNo,
      ...newOrderForm,
      orderStatus: '待提交',
      registeredIncome: 0,
      uncollectedAmount: newOrderForm.orderAmount,
      auditedIncome: 0,
      expendAmount: 0,
      refundAmount: 0,
      customerDepartment: '', // 可根据实际需求补充
      signerDepartment: '', // 可根据实际需求补充
    };
    
    // 添加到当前标签页数据中
    mockData.value.unshift(newOrder);
    
    // 如果当前标签页是"待提交"，直接显示；否则仅在全部标签页显示
    if (activeName.value === 'toSubmit') {
      mockData.value.unshift(newOrder);
    }
    
    closeAddOrderDialog();
    ElMessage.success('订单创建成功');
  } catch (error) {
    return false;
  }
};

// 提交新增客户
const submitNewCustomer = async () => {
  try {
    await customerFormRef.value.validate();
    
    // 校验客户编号唯一性
    const exists = customerData.value.some(
      item => item.customerNo === newCustomerForm.customerNo
    );
    
    if (exists) {
      ElMessage.error('客户编号已存在');
      return;
    }
    
    // 添加新客户到客户列表
    customerData.value.push({ ...newCustomerForm });
    handleCustomerSearch();
    
    // 自动选择新增的客户
    selectCustomer({ ...newCustomerForm });
    
    showAddCustomer.value = false;
    customerFormRef.value.resetFields();
    ElMessage.success('客户新增成功');
  } catch (error) {
    return false;
  }
};

// 页面挂载时初始化
onMounted(() => {
  handleTabChange('all');
  filteredCustomers.value = [...customerData.value];
});
</script>

<style lang="less" scoped>
.my-clue {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f7fa;
  overflow: hidden;
  position: relative;
}

/* 主内容区移位控制 */
.main-content {
  width: 100%;
  transition: width 0.3s ease;
  
  &.shift-left {
    width: 50% !important; /* 确保收缩到50% */
  }
}

.top-filter {
  width: 100%;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  padding: 0 20px;
  box-sizing: border-box;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;

  .top-filter-left {
    display: flex;
    align-items: center;
    gap: 15px;

    .top-filter-btn {
      display: flex;
      align-items: center;
      gap: 5px;
      padding: 0 15px;
      height: 32px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.2s;

      &:hover {
        border-color: #409eff;
        color: #409eff;
      }
    }

    .top-filter-search {
      width: 260px;
    }
  }

  .top-filter-right {
    display: flex;
    gap: 10px;
  }
}

.table-area {
  width: calc(100% - 40px);
  margin: 20px auto;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  padding: 16px;
  box-sizing: border-box;

  .table-area-tab {
    margin-bottom: 8px;
    display: flex;
    justify-content: flex-start;

    .tab-wrapper {
      display: flex;
      align-items: center;
      max-width: 100%;
      width: auto;

      .demo-tabs {
        flex: 1;
        margin-right: 10px;
        max-width: calc(100% - 60px);
      }

      .more-tab {
        display: flex;
        align-items: center;
        gap: 4px;
        color: #606266;
        cursor: pointer;
        padding: 5px 10px;
        border-radius: 4px;
        transition: background-color 0.2s, color 0.2s;
        min-width: 50px;
        justify-content: center;

        &:hover {
          background-color: #f5f7fa;
          color: #409eff;
        }

        .arrow-icon {
          font-size: 14px;
        }
      }
    }
  }

  .table-area-table {
    width: 100%;
    overflow-x: hidden;

    .el-table__cell {
      padding: 10px 8px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
}

.top-filter-form {
  padding: 15px;
  width: 400px;

  .el-form-item {
    margin-bottom: 15px;
  }
}

.top-filter-operate {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 10px 15px;
  border-top: 1px solid #f0f0f0;
}

.filter-icon {
  margin-left: 5px;
  color: #c0c4cc;
  cursor: pointer;
  font-size: 16px;
}

/* 右侧弹窗核心样式 */
.right-dialog {
  position: fixed;
  top: 0;
  right: 0;
  width: 50%; /* 固定右侧50%宽度 */
  height: 100vh; /* 全屏高度 */
  background: #fff;
  border-left: 1px solid #e5e7eb;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.05);

  .dialog-header {
    padding: 16px 20px;
    border-bottom: 1px solid #e5e7eb;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }

    .close-btn {
      width: 36px;
      height: 36px;
      padding: 0;
      font-size: 20px;
    }
  }

  .dialog-body {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
  }

  .dialog-footer {
    padding: 12px 20px;
    border-top: 1px solid #e5e7eb;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}

/* 遮罩层样式 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background: rgba(0, 0, 0, 0.1);
  z-index: 999;
  cursor: pointer;
}

/* 客户搜索相关样式 */
.dialog-toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}

.add-customer-btn {
  color: #409eff;
  padding: 5px 10px;

  &:hover {
    color: #66b1ff;
    background-color: #ecf5ff;
  }
}

.customer-list {
  flex: 1;
  overflow-y: auto;
}

.no-data {
  text-align: center;
  padding: 60px 0;
  color: #909399;

  .no-data-icon {
    font-size: 48px;
    margin-bottom: 15px;
    color: #c0c4cc;
  }

  .no-data-text {
    font-size: 16px;
    margin-bottom: 8px;
  }

  .no-data-hint {
    font-size: 14px;
    color: #c0c4cc;
  }
}

.new-order-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.new-customer-form {
  .el-form-item {
    margin-bottom: 15px;
  }
}
</style>